package com.zzkrst.modules.generator.service.impl;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzkrst.modules.generator.mapper.SysGeneratorMapper;
import com.zzkrst.modules.generator.model.GeneratorParam;
import com.zzkrst.modules.generator.service.SysGeneratorService;
import com.zzkrst.modules.generator.utils.GenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.configuration.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipOutputStream;

/**
 * @Author zlt
 */
@Slf4j
@Service
public class SysGeneratorServiceImpl  implements SysGeneratorService {
    @Autowired
    private SysGeneratorMapper sysGeneratorMapper;

    @Override
    public IPage<List<Map<String, Object>>> queryList(String tableName, Integer pageNo, Integer pageSize) {
        Page<Map<String, Object>> page = new Page<>(pageNo,pageSize);

        IPage<List<Map<String, Object>>> list = sysGeneratorMapper.queryList(page, tableName);
        return list;
    }

    @Override
    public Map<String, String> queryTable(String tableName) {
        return sysGeneratorMapper.queryTable(tableName);
    }

    @Override
    public List<Map<String, String>> queryColumns(String tableName) {
        return sysGeneratorMapper.queryColumns(tableName);
    }

    @Override
    public GeneratorParam queryGeneratorParam(String tableName) {
        GeneratorParam param = new GeneratorParam();
        param.setToPath(System.getProperty("user.dir"));
        param.setTableClassName(GenUtils.tableToJava(tableName,""));
        Configuration config = GenUtils.getConfig();
        param.setAuthor(config.getString("author"));
        param.setPackageName(config.getString("package"));
        return param;
    }

    @Override
    public byte[] generatorCode(GeneratorParam param) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //查询列信息
        List<Map<String, String>> columns = queryColumns(param.getTableName());
        //生成代码
        GenUtils.generatorCode(zip, columns, param);

        IoUtil.close(zip);
        return outputStream.toByteArray();
    }



}
